const conn = require("../../data/index");
// 渲染posts页面
module.exports.posts = (req, res) => {
  res.render("background/posts");
};

// 进行分页渲染
module.exports.postsShow = (req, res) => {
  // 1.声明变量 pageNum
  let pageNum = req.query.pageNum;
  let pageSize = req.query.pageSize;
  let indexStart = (pageNum - 1) * pageSize;
  // console.log(req.query);
  conn.query(
    `SELECT count(*) as total from page_news;
  select  page_news.id,title,author,page_options.option,created_at,clickrate 
  from page_news , page_options where page_options.id=page_news.page_options_id
  LIMIT ${indexStart},${pageSize}`,
    (error, results) => {
      if (error) return console.log(error);
      // console.log(results);
      res.json({
        pageNum: pageNum,
        pageSize: pageSize,
        dataTotal: results[0][0].total,
        data: results[1]
      });
    }
  );
};
// 文章管理页的删除功能
module.exports.postsRemove = (req, res) => {
  // console.log(req.query);
  conn.query(
    "delete from page_news where id=?",
    [req.query.id],
    (error, results) => {
      if (error) return console.log(error);
      res.json({
        code: "1201",
        message: "删除数据成功"
      });
    }
  );
};
// // 文件搜索功能
// module.exports.postsSearch = (req, res) => {
//   console.log(req.query);

// }

// 进行分页渲染
module.exports.postsSearch = (req, res) => {
  // console.log(req.query);
  // 1.声明变量 pageNum
  let pageNum = req.query.pageNum;
  let pageSize = req.query.pageSize;
  let indexStart = (pageNum - 1) * pageSize;
  // console.log(req.query);
  conn.query(
    `SELECT count(*) as total from page_news;
  select  page_news.id,title,author,page_options.option,created_at,clickrate 
  from page_news , page_options where page_options.id=page_news.page_options_id and page_news.title like "%${
    req.query.keyword
  }%"
  `,
    (error, results) => {
      if (error) return console.log(error);
      // console.log(results);
      res.json({
        pageNum: pageNum,
        pageSize: pageSize,
        dataTotal: results[0][0].total,
        data: results[1]
      });
    }
  );
};
